﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using System.IO;
using TaoLeH.Helper;
using TaoLeH.Models.Dto;
using TaoLeH.Helper.Json;
using TaoLeH.Models.Enum;
using TaoLeH.Helper.Config;
using System.Collections;

namespace TaoLeH.WebApi.Controllers
{
    /// <summary>
    /// api请求统一入口 leev 2018-03-28
    /// </summary>
    /// [Produces("application/json")]
    [Route("api/GateWay")]
    public class GateWayController : Controller
    {
        /// <summary>
        /// api请求
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Post()
        {
            ApiContext apiContext = new ApiContext();
            ApiHttpResponse apiResp = new ApiHttpResponse();

            try
            {
                if (HttpContext.Request.ContentLength != null)
                {
                    //接收post流转换为字符串
                    Stream stream = HttpContext.Request.Body;
                    byte[] buffer = new byte[HttpContext.Request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);
                    string postdata = Encoding.UTF8.GetString(buffer);

                    //LogHelper.Info("API请求入口接收参数:", postdata);

                    ApiHttpRequest apiReq = null;
                    //1. 解析请求数据
                    try
                    {
                        apiReq = JsonHelper.Deserialize<ApiHttpRequest>(postdata);
                        apiReq.Data = ApiHelper.ConvertToBase64Str(apiReq.Data);
                    }
                    catch (Exception ex)
                    {
                        //LogHelper.Error("统一入口解析异常", $"{postdata},{ex.Message},{HttpContext.Request.ContentLength.Value}");
                    }

                    if (apiReq != null)
                    {
                        //2. 检查通用参数
                        if (string.IsNullOrEmpty(apiReq.MerNo) || string.IsNullOrEmpty(apiReq.Service)
                            || string.IsNullOrEmpty(apiReq.Sign) || string.IsNullOrEmpty(apiReq.TimeStamp))
                        {
                            apiResp.RetCode = ResultEnum.ParamError;
                            apiResp.Message = "缺少请求参数";
                            apiContext.ApiHttpResp = apiResp;
                            return apiContext.ReturnResp();
                        }

                        //验证时间戳是否有效
                        if (!ApiHelper.CheckTimeStamp(ConvertHelper.ConvertTo<int>(apiReq.TimeStamp, 0), ApiConfig.ServerConfigs.SystemConfig.TimeValid))
                        {
                            apiResp.RetCode = ResultEnum.TimeError;
                            apiResp.Message = "请求已失效";
                            apiContext.ApiHttpResp = apiResp;
                            return apiContext.ReturnResp();
                        }

                        //3. 检查商户信息,这里暂时先写死
                        if (apiReq.MerNo != ApiConfig.ServerConfigs.SystemConfig.ValidMerNo)
                        {
                            apiResp.RetCode = ResultEnum.ParamError;
                            apiResp.Message = "商户不存在或禁用";
                            apiContext.ApiHttpResp = apiResp;
                            return apiContext.ReturnResp();
                        }

                        //4. 检查签名
                        apiContext.MerKey = ApiConfig.ServerConfigs.SystemConfig.MerKey;
                        //请求类转hashtable
                        Hashtable ht = ModelHandler<ApiHttpRequest>.TransforClass(apiReq);
                        if (!ApiHelper.CheckSign(ht, apiContext.MerKey))
                        {
                            apiResp.RetCode = ResultEnum.SignError;
                            apiResp.Message = "签名失败";
                            apiContext.ApiHttpResp = apiResp;
                            return apiContext.ReturnResp();
                        }

                        //5. base64解密data
                        apiContext.DecData = ApiHelper.DecodeBase64(apiReq.Data);
                        //这里统一判断解密后data是否为空，具体api接口不在判断！！！
                        //某些接口data可为空情况，这里在加一层判断，整理出哪些不需data的接口，绕过此判断
                        if (string.IsNullOrEmpty(apiContext.DecData))
                        {
                            apiResp.RetCode = ResultEnum.ParamError;
                            apiResp.Message = "请求数据为空";
                            apiContext.ApiHttpResp = apiResp;
                            return apiContext.ReturnResp();
                        }

                        apiContext.ApiHttpReq = apiReq;

                        //6. 执行方法
                        var DoAction = DelegateFactory.GetDoAction(apiReq.Service);
                        if (DoAction == null)
                        {
                            apiResp.RetCode = ResultEnum.NoService;
                            apiResp.Message = "服务不存在";
                            apiContext.ApiHttpResp = apiResp;
                            return apiContext.ReturnResp();
                        }
                        //6. 执行方法
                        DoAction(apiContext);
                    }
                    else
                    {
                        apiResp.RetCode = ResultEnum.AnalyticError;
                        apiResp.Message = "json序列化失败";
                        apiContext.ApiHttpResp = apiResp;
                    }
                }
                else
                {
                    apiResp.RetCode = ResultEnum.NoData;
                    apiResp.Message = "无请求数据";
                    apiContext.ApiHttpResp = apiResp;
                }

                return apiContext.ReturnResp();
            }
            catch (Exception e)
            {
                apiResp.RetCode = ResultEnum.ServiceException;
                apiResp.Message = "服务异常";
                apiContext.ApiHttpResp = apiResp;
                //LogHelper.Error("API请求入口异常:", e.Message + " 原因:" + e.StackTrace);
                return apiContext.ReturnResp();
            }
        }
    }
}
